package com.inepex.inechart.client.displayengine;

import java.util.TreeMap;

public class TileTable {

	public class Row{
		protected final int id;
		protected TreeMap<Integer, RectangleTile> tiles;
		
		public Row(int id) {
			this.id = id;
			this.tiles = new TreeMap<Integer, RectangleTile>();
		}
		
		protected void addTile(RectangleTile tile){
			tile.setColumn(tiles.lastKey() + 1);
			tiles.put(tile.getColumn(), tile);
		}
		
		protected void addTile(RectangleTile tile, int col){
			tile.setColumn(col);
			tiles.put(col, tile);
		}
		
		protected RectangleTile getTile(int col){
			return tiles.get(col);
		}
		
	}
		
	protected TreeMap<Integer, Row> rows;
	protected Row actualRow;
	
	public TileTable() {
		rows = new TreeMap<Integer, TileTable.Row>();
	}

	public void newRow(){
		int rowId = rows.size() == 0 ? 0 : rows.lastKey() + 1;
		actualRow = new Row(rowId);
		rows.put(rowId, actualRow);
	}
	
	public void addTile(RectangleTile tile){
		if(rows.size() == 0){
			newRow();
		}
		tile.setRow(actualRow.id);
		actualRow.addTile(tile);
	}
	
	protected Row getOrCreateRow(int row){
		Row r = rows.get(row);
		if(r == null){
			r = new Row(row);
			rows.put(row, r);
		}
		return r;
	}

	public void setTile(RectangleTile tile, int row, int col){
		tile.setRow(row);
		tile.setColumn(col);
		getOrCreateRow(row).addTile(tile, col);
	}

	public RectangleTile getTile(int row, int col){
		Row r = rows.get(row);
		return r == null ? null : r.getTile(col);
	}
	
	public void clear(){
		rows.clear();
		actualRow = null;
	}
	
	public void setTileSizes(int width, int height){
		for (int row : rows.keySet()) {
			for (int col : rows.get(row).tiles.keySet()) {
				rows.get(row).tiles.get(col).setSize(width, height);
			}
		}
	}
}
